<template>
  <div>
    <el-table
      :data="state.tableData"
      id="table"
      :row-class-name="rowheight"
      :header-row-class-name="headerHeight"
      :header-cell-style="{
        'text-align': 'center',
        'font-weight': '400',
      }"
      :cell-style="{ 'text-align': 'center' }"
      class="customer-table text-18"
      style="width: 100%"
      max-height="555"
    >
      <el-table-column prop="project_name" :label="$t('financial.Item')">
      </el-table-column>
      <el-table-column
        prop="project_currency_name"
        :label="
          isHosting && active === 1
            ? $t('hosting.CustodyCurrency')
            : $t('financial.MoneyCurrency')
        "
      >
      </el-table-column>
      <el-table-column prop="project_arp" :label="$t('freeMoney.returnRate')">
        <template #default="r">
          <span
            >{{ decimalDigitsInputFilter(r.row.project_arp * 100, 4) }}%({{
              r.row.project_arp_type === 1
                ? $t("financial.yearRate")
                : r.row.project_arp_type === 2
                ? $t("financial.annualizedRate")
                : $t("financial.dailyRate")
            }})</span
          >
        </template>
      </el-table-column>
      <!-- <el-table-column
        v-if="active === 2"
        prop="project_arp"
        :label="$t('stock.annualizedRate')"
      >
        <template #default="r">
          <span
            >{{ decimalDigitsInputFilter(r.row.project_arp * 100, 4) }}%</span
          >
        </template>
      </el-table-column> -->
      <el-table-column
        prop="project_deadline_day"
        :label="
          isHosting && active === 1
            ? $t('hosting.EscrowPeriod')
            : $t('financial.investmentPeriod')
        "
      >
        <template #default="r">{{
          active === 1 ? r.row.project_deadline_day : $t("stock.anyStorage")
        }}</template>
      </el-table-column>
      <el-table-column
        v-if="active === 1"
        prop="currency_amount"
        :label="$t('freeMoney.orderNumber')"
      >
        <template #default="r"
          >{{ $currency(r.row.order_share)
          }}{{ $t("financial.share") }}</template
        >
      </el-table-column>
      <el-table-column
        v-if="active === 1"
        prop="currency_amount"
        :label="
          isHosting && active === 1
            ? $t('hosting.ActualCustodyCopies')
            : $t('freeMoney.actualNumber')
        "
      >
        <template #default="r"
          >{{ $currency(r.row.active_share) }}{{ $t("financial.share") }}/{{
            $currency(r.row.currency_amount)
          }}{{ r.row.project_currency_name }}</template
        >
      </el-table-column>
      <el-table-column
        v-if="active === 2"
        prop="order_share"
        :label="$t('stock.ordersNumber')"
      >
        <template #default="r">{{ $currency(r.row.order_share) }}</template>
      </el-table-column>
      <el-table-column
        v-if="active === 2"
        prop="active_share"
        :label="$t('stock.actualOrdersNumber')"
      >
        <template #default="r"
          >{{ $currency(r.row.active_share) }}{{ $t("financial.share") }}/{{
            $currency(r.row.currency_amount) + r.row.project_currency_name
          }}</template
        >
      </el-table-column>
      <el-table-column
        v-if="active === 1"
        prop="expected_profits"
        :label="$t('financial.expectedReturn')"
      >
        <template #default="r">
          <span>
            {{ $currency(dolt(r.row.expected_profits)) }}
            {{ r.row.project_currency_name }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="active === 2"
        prop="expected_profits"
        :label="$t('stock.Earned')"
      >
        <template #default="r">
          <span>
            {{
              r.row.order_status === 0
                ? "0"
                : $currency(dolt(r.row.expected_profits))
            }}
            {{ r.row.project_currency_name }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="active === 1"
        prop="expected_end_time"
        :label="$t('financial.expectedEndTime')"
      >
        <template #default="r">
          <span>
            {{
              getTimeZoneDate(
                r.row.create_time +
                  r.row.project_deadline_day * 24 * 60 * 60 * 1000
              )
            }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="active === 2"
        prop="create_time"
        :label="$t('assets.time')"
      >
        <template #default="r">
          <span>
            {{ getTimeZoneDate(r.row.create_time) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="order_status">
        <template #header>
          <el-dropdown trigger="click" @command="menuCommand">
            <span class="el-dropdown-link">
              {{ state.status
              }}<i class="el-icon-caret-bottom text-16 ml-5"></i>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="-1">{{
                  $t("financial.all")
                }}</el-dropdown-item>
                <!-- <el-dropdown-item command="0">{{
                  $t("financial.allocating")
                }}</el-dropdown-item> -->
                <el-dropdown-item command="1">{{
                  isHosting && active === 1
                    ? $t("hosting.InHosting")
                    : $t("financial.Financialing")
                }}</el-dropdown-item>
                <el-dropdown-item command="2">{{
                  $t("financial.over")
                }}</el-dropdown-item>
                <el-dropdown-item command="3">
                  {{ $t("cancelFinancial.Cancelled") }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
        <template #default="r">
          <div
            :class="
              r.row.order_status == 0
                ? 'text-link'
                : r.row.order_status == 1
                ? 'text-link'
                : 'quotet3'
            "
          >
            {{
              r.row.order_status == 0
                ? $t("financial.allocating")
                : r.row.order_status == 1
                ? isHosting && active === 1
                  ? $t("hosting.InHosting")
                  : $t("financial.Financialing")
                : r.row.order_status == 2
                ? $t("financial.over")
                : $t("cancelFinancial.Cancelled")
            }}
          </div>
          <div
            class="text-link text-10"
            v-if="
              r.row.order_status == 3 && r.row.cancel_set_info?.cancel_status
            "
          >
            <div>
              {{ $t("cancelFinancial.damages") }}:{{
                $currency(r.row.liquidated_damages)
              }}{{ r.row.project_currency_name }}
            </div>
            <div>{{ getTimeZoneDate(r.row.cancel_time) }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="expected_end_time" :label="$t('assets.operate')">
        <template #default="r">
          <div v-if="active === 1">
            <el-button
              type="text"
              class="color-98 free-box"
              @click="
                seeIncome(
                  r.row.user_revenue_log_list,
                  r.row.project_currency_name,
                  r.row.id
                )
              "
              >{{ $t("financial.viewEarning") }}</el-button
            >
            <div>
              <el-button
                v-if="r.row.balance_type === 2"
                type="text"
                class="color-98 free-box"
              >
                {{
                  isHosting && active === 1
                    ? $t("hosting.ManagedTrialMoney")
                    : $t("freeMoney.experienceGold")
                }}
              </el-button>
            </div>
            <div>
              <el-button
                v-if="
                  (r.row.order_status == 0 || r.row.order_status == 1) &&
                    r.row.cancel_set_info?.cancel_status
                "
                type="text"
                @click="cancelPop(r.row)"
                class="text-warning warning-hover wrap-btn"
              >
                {{
                  isHosting && active === 1
                    ? $t("hosting.cancelEscrow")
                    : $t("cancelFinancial.CancelWeath")
                }}
              </el-button>
            </div>
          </div>
          <div v-else>
            <el-button
              type="text"
              v-if="
                (r.row.order_status == 0 || r.row.order_status == 1) &&
                  r.row.cancel_set_info?.cancel_status &&
                  r.row.balance_type === 1
              "
              @click="handleTakeOut(r.row.id)"
              >{{ $t("stock.takeOut") }}</el-button
            >
          </div>
        </template>
      </el-table-column>
      <template #empty>
        <div>
          <Norecord />
        </div>
      </template>
    </el-table>
    <!-- 收益明细 -->
    <el-dialog
      :title="$t('financial.incomeBreakdown')"
      v-model="state.dialogVisible"
      width="400px"
    >
      <div class="pb-dialog">
        <div class="flex align-center js-sp dialog-title">
          <div>{{ $t("financial.gainProfit") }}</div>
          <div>{{ $t("financial.earningTime") }}</div>
        </div>
        <EarningDetail
          :list="state.incomeList"
          :currency="state.currency"
          :id="state.id"
        ></EarningDetail>
      </div>
    </el-dialog>
    <!-- 提前取消理财 -->
    <el-dialog
      :title="$t('formTip.tip')"
      v-model="state.cancelVisible"
      width="400px"
    >
      <div class="text-left p-30">
        <div class="color-1e mb-10">
          {{
            isHosting && active === 1
              ? $t("hosting.cancelTip")
              : $t("cancelFinancial.cancelTip")
          }}
        </div>
        <div class="text-14 color-98 mb-30">
          <div v-if="state.detailInfo.cancel_set_info?.handling_fee != -1">
            {{ $t("financial.deductionFee") }}：{{
              state.detailInfo.cancel_set_info?.handling_fee
            }}%
          </div>
          <div v-if="state.detailInfo.cancel_set_info?.day_interest != -1">
            {{ $t("financial.holdingPeriod") }}：{{
              state.detailInfo.cancel_set_info?.day_interest
            }}%（{{ $t("financial.dailyEarnings") }}）
          </div>
          <div v-if="state.detailInfo.cancel_set_info?.return_amount != -1">
            {{ $t("financial.returnBalance") }}：<span
              class="color-1e text-bold"
              >{{ state.detailInfo.cancel_set_info?.return_amount }}</span
            >
            {{ state.detailInfo.project_currency_name }}
          </div>
        </div>
        <div class="flex js-sp buble-t1">
          <div
            class="letter-btn text-center nobtn point"
            @click="state.cancelVisible = false"
          >
            {{ $t("formTip.cancel") }}
          </div>
          <div
            class="letter-btn acbtn point text-center"
            @click="confirm(state.detailInfo.id)"
          >
            {{ $t("formTip.comfirm") }}
          </div>
        </div>
      </div>
    </el-dialog>
    <!-- 取出 -->
    <el-dialog
      :title="$t('formTip.tip')"
      v-model="state.takeOutVisible"
      width="400px"
    >
      <div class="text-left p-30">
        <div class="color_1e mb-10">{{ $t("stock.takeOutTip") }}</div>
        <div class="text-14 color_98 mb-30">
          {{ $t("stock.noIncomeTip") }}
        </div>
        <div class="flex js-sp buble-t1">
          <div class="letter-btn text-center nobtn point" @click="cancer">
            {{ $t("formTip.cancel") }}
          </div>
          <div
            class="letter-btn acbtn point text-center"
            @click="confirm(state.id)"
          >
            {{ $t("formTip.comfirm") }}
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Norecord from "@/components/noRecord/NoRecord.vue";
import EarningDetail from "@/components/defiMining/earningDetail.vue";
import { onMounted, reactive, watch } from "vue";
// import { useStore } from "vuex";
import {
  LoginInterception,
  decimalDigitsInputFilter,
  transferToNumber,
} from "@/utils/common";
import { getTimeZoneDate, formatDate } from "@/utils/times.js";
import {
  userWealthManagementPage,
  userWealthManagement,
  cancelWealthManagement,
} from "@/api/wealth";
import { useI18n } from "vue-i18n";
import { rideFix } from "@/utils/precisionMath";
import { ElMessage } from "element-plus";

export default {
  name: "CurentCommin",
  emits: [
    "getAll",
    "miningRightNow",
    "changeType",
    "refresh",
    "getArraryLength",
  ],
  props: { listParam: Object, active: Number, isHosting: Boolean },
  components: { Norecord, EarningDetail },
  setup(props, { emit }) {
    // const $store = useStore();
    const { t } = useI18n();
    const state = reactive({
      dialog: false,
      tableData: [],
      listParam: {
        page: props.page,
        limit: 10,
      },
      loading: false,
      total: 0,
      status: t("financial.all"),
      currentpage: 1,
      dialogVisible: false,
      cancelVisible: false,
      takeOutVisible: false,
      assetsParam: {
        limit: 10,
        page: 0,
      },
      incomeList: [],
      items: [],
      currency: "",
      id: 0,
      type: "",
    });

    onMounted(() => {
      getList();
    });

    // 表格行高度
    const rowheight = () => {
      return "table-rowheight";
    };
    const headerHeight = () => {
      return "table-header";
    };
    watch(
      () => props.listParam.page,
      (val, oldval) => {
        console.log(val, oldval);
        if (val != oldval && state.type !== "cancelRefresh") {
          getList();
        }
      }
    );
    watch(
      () => props.listParam.order_status,
      (val, oldval) => {
        console.log(val, oldval);
        // props.listParam.page = 0;
        state.tableData = [];
        getList();
      }
    );
    watch(
      () => props.active,
      () => {
        emit("refresh");
        state.tableData = [];
        getList();
      }
    );
    const refresh = () => {
      // props.listParam.page = 0;
      getList();
    };
    const seeIncome = (val, currency, id) => {
      state.incomeList = [...val];
      state.dialogVisible = true;
      state.total = val?.length;
      state.currency = currency;
      state.id = id;
      getDetail(id);
    };
    const getDetail = (id) => {
      userWealthManagement(id).then((res) => {
        state.incomeList = [...res.data.user_revenue_log_list];
      });
    };
    const menuCommand = (val) => {
      if (val > -1) {
        if (val == 0) {
          state.status = t("financial.allocating");
        } else if (val == 1) {
          state.status =
            props.isHosting && props.active === 1
              ? t("hosting.InHosting")
              : t("financial.Financialing");
        } else {
          state.status = t("financial.over");
        }
        emit("changeType", val);
      } else {
        state.status = t("financial.all");
        emit("changeType", null);
      }
    };
    const getList = () => {
      LoginInterception("/myDefi").then(() => {
        const data = { ...props.listParam };
        data.management_type = props.active;
        state.loading = true;
        userWealthManagementPage(data)
          .then((res) => {
            if (state.type === "cancelRefresh") {
              state.type = "";
            }
            state.loading = false;
            let ary = [...state.tableData];
            state.tableData = [...ary, ...res.data.items];
            if (
              state.tableData.length === res.data.total ||
              res.data.items.length < props.listParam.limit
            ) {
              emit("getAll", true);
            } else {
              emit("getAll", false);
            }
            emit("getArraryLength", res.data.total);
            // state.total = res.data.total
          })
          .catch((err) => {
            console.log(err);
          });
      });
    };
    const dolt = (val) => {
      return transferToNumber(val);
    };
    const cancelPop = (r) => {
      state.detailInfo = { ...r };
      state.cancelVisible = true;
    };
    const confirm = (id) => {
      onCancelWealthManagement(id);
    };
    const cancer = () => {
      state.takeOutVisible = false;
    };
    //取消理财
    const onCancelWealthManagement = (id) => {
      state.type = "cancelRefresh";
      cancelWealthManagement(id).then(() => {
        state.takeOutVisible = false;
        state.cancelVisible = false;
        emit("refresh");
        if (state.active === 2) {
          ElMessage.success(t("stock.takeOutSuccessTip"));
        }
        state.tableData = [];
        getList();
      });
    };
    const handleTakeOut = (id) => {
      state.takeOutVisible = true;
      state.id = id;
    };
    return {
      state,
      getList,
      getTimeZoneDate,
      refresh,
      rowheight,
      headerHeight,
      LoginInterception,
      formatDate,
      menuCommand,
      seeIncome,
      getDetail,
      decimalDigitsInputFilter,
      dolt,
      rideFix,
      confirm,
      cancelPop,
      onCancelWealthManagement,
      handleTakeOut,
      cancer,
    };
  },
};
</script>

<style scoped lang="less">
.close-btn {
  width: 114px;
  height: 30px;
  line-height: 30px;
}
.mb-24 {
  margin-bottom: 24px;
}
.pb-dialog {
  padding: 14px 20px;
  .dialog-title {
    color: #989898;
    font-size: 12px;
    line-height: 17px;
    margin-bottom: 14px;
  }
  .items {
    font-weight: bold;
    font-size: 12px;
    line-height: 15px;
    color: #424344;
    margin-bottom: 10px;
  }
}
.letter-tip {
  width: 100%;
}
.letter-btn {
  width: 160px;
  height: 46px;
  line-height: 46px;
  border-radius: 4px;
}
.pop-img {
  width: 100px;
  height: 100px;
}
.text-14 {
  font-weight: normal;
  font-size: 14px;
  line-height: 20px;
}
.color-42 {
  color: #424344;
}

.color-blue {
  color: #2e96f6;
}
.color-1e {
  color: #121212;
}
.color-98 {
  color: #989898;
}
.mb-30 {
  margin-bottom: 30px;
}
.mb-10 {
  margin-bottom: 10px;
}
.p-30 {
  padding: 14px 20px;
}
.free-box {
  width: 100%;
  white-space: break-spaces;
}
.wrap-btn {
  white-space: normal;
}
</style>
